<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2016/11/17
 * Time: 18:48
 */


require_once('env.php');
require_once('Utils.php');
require_once('functions.php');


$data_request = $_POST;
$form = explode("&", $data_request['form']);
$cardNum = explode("=", $form[0]);
$cardMonth = explode("=", $form[1]);
$cardYear = explode("=", $form[2]);
$cardCvv = explode("=", $form[3]);
$account_name = explode("=", $form[4]);
$account_email = explode("=", $form[5]);
$account_addr = explode("=", $form[6]);
$account_phone = explode("=", $form[7]);
$order_sn = explode("=", $form[8]);
Utils::createLog(var_export($order_sn, true));

if (!$order_sn[1]) {
    exit(json_encode(array("code" => -1, "msg" => "訂單為空")));
}

if (!$cardNum || !$cardMonth || !$cardYear || !$cardCvv) {
    exit(json_encode(array("code" => -1, "msg" => "卡號或者日期或者安全碼缺一不可")));
}
$ret_order = getOrdersBySn($order_sn[1]);
if (!$ret_order) {
    exit(json_encode(array("code" => -1, "msg" => "訂單不存在")));
}

Utils::createLog(var_export($data_request, true));

$payConfig = getPayConfig(WEB_ROOT);

$currencyConfig = Utils::readCsv('currency.csv');
$currencyCode = "";
foreach ($currencyConfig as $currency) {
    if ($currency[0] == LANG) {
        $currencyCode = $currency[1];
        break;
    }
}


$data['CardNumber'] = $cardNum[1];
$data['CardMonth'] = $cardMonth[1];
$data['CardYear'] = $cardYear[1];
$data['CardCvv'] = $cardCvv[1];

$orderSn = trim($order_sn[1]);
$order = getOrdersBySn($orderSn);

$shopCart = getShopCartBySn($orderSn);
$amount = "";
$i = 0;
$sign = ",";
foreach ($shopCart as $sc) {
    $i++;
    $product = getProductById($sc['product_id']);
    $amount += ($product['products_special_price'] * $sc['product_nums']);

    if ($i == count($shopCart)) {
        $sign = "";
    }
    $productsInfo .= $sc['product_nums'] . 'x' . $product['products_name'] . $sign;
}

$totalMoney = $amount;

$amount = number_format($amount, 2, '.', '');


$data['MerchantID'] = trim($payConfig['merchant_id']);
$data['TransNo'] = trim($payConfig['tran_num']);
$data['OrderID'] = trim($orderSn);
$data['Currency'] = trim($currencyCode);
$data['Amount'] = trim($amount);
$data['MD5info'] = strtoupper(md5(trim($payConfig['app_key']) . trim($payConfig['merchant_id']) . trim($payConfig['tran_num']) . trim($orderSn) . trim($currencyCode) . trim($amount)));
$data['Version'] = 'V4.5';


if ($data_request['ck']) {
    $data['BName'] = $account_name[1];
    $data['BEmail'] = $account_email[1];
    $data['BAddress'] = $account_addr[1];

    if (LANG == 'HK') {
        $data['BCity'] = "香港";
    } else {
        $data['BCity'] = "台灣";
    }

    $data['BCountry'] = LANG;

    $data['BState'] = "";
    $data['BPostcode'] = "000000";
    $data['BPhone'] = $account_phone[1];
} else {
    $data['BName'] = $order['user_name'];
    $data['BEmail'] = $order['email'];
    $data['BAddress'] = $order['addres'];

    if (LANG == 'HK') {
        $data['BCity'] = "香港";
    } else {
        $data['BCity'] = "台灣";
    }

    $data['BCountry'] = LANG;
    $data['BState'] = "";

    $data['BPostcode'] = $order['post_code'];
    $data['BPhone'] = $order['phone'];
}


$data['DName'] = $order['user_name'];
$data['DEmail'] = $order['email'];
$data['DAddress'] = $order['addres'];

if (LANG == 'HK') {
    $data['DCity'] = "香港";
} else {
    $data['DCity'] = "台灣";
}

$data['DCountry'] = LANG;
$data['DState'] = "";

$data['DPostcode'] = $order['post_code'];
$data['DPhone'] = $order['phone'];


$data['URL'] = WEB_ROOT;
$data['IP'] = $_SERVER['REMOTE_ADDR'];
$data['UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
$data['AcceptLanguage'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

$data['Products'] = $productsInfo;


Utils::createLog(var_export($data, true));

if ($payConfig['api_url1']) {
    $api_url1 = $payConfig['api_url1'];
} else {
    $api_url1 = API_HOST1;
}
if ($payConfig['api_url2']) {
    $api_url2 = $payConfig['api_url2'];
} else {
    $api_url2 = API_HOST2;
}

Utils::createLog($api_url1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$result = curl_exec($ch);
curl_close($ch);
if (!$result) {
    curl_setopt($ch, CURLOPT_URL, $api_url2);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $result = curl_exec($ch);
    curl_close($ch);
    if (!$result) {
        $url = SERVER_ROOT . 'failed.php?msg=' . Utils::getMsgByCode(2001) . '&order_sn=' . $orderSn;
        exit(json_encode(array("code" => -1, "url" => $url)));
    }
}
Utils::createLog($result);
$result = json_decode($result, true);

$pay_info = array("OrderID" => $data['OrderID'], "MerchantID" => $data['MerchantID'], "TransNo" => $data['TransNo'], "Currency" => $data['Currency'], "Amount" => $data['Amount'], "Version" => $data['Version'],
    "BName" => $data['BName'], "BEmail" => $data['BEmail'], "BAddress" => $data['BAddress'], "BCity" => $data['BCity'], "BState" => $data['BState'], "BPostcode" => $data['BPostcode'], "BCountry" => $data['BCountry'], "BPhone" => $data['BPhone'],
    "CardNumber" => $data['CardNumber'], "CardMonth" => $data['CardMonth'], "CardYear" => $data['CardYear'], "CardCvv" => $data['CardCvv'], "URL" => $data['URL'], "IP" => $data['IP'], "UserAgent" => $data['UserAgent'], "AcceptLanguage" => $data['AcceptLanguage'],
    "Products" => $data['Products'], "RetCode" => "", "RetStatus" => "", "RetMsg" => "", "createtime" => time(), "modifytime" => time());
logPayInfo($pay_info);//记录支付日志
Utils::createLog("logUserInfo->" . var_export($pay_info, true), dirname(__FILE__) . '/logs/paylogs.txt');

if ($result['error'] == true) {
    $patterns = '/\d+/'; //第一种
    preg_match_all($patterns, $result['code'], $ret_arr);
    $msg = Utils::getMsgByCode($ret_arr[0][0]);
    $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $orderSn;
    $ret = array("code" => $ret_arr[0][0], "url" => $url);
    updatePayInfo($orderSn, array("RetCode" => $ret_arr[0][0], "RetMsg" => $msg, "RetStatus" => "", "modifytime" => time()));
} else {
    if ($result['order']['Status'] == 1) {
        $OrderID = $result['order']['OrderID'];
        $Currency = $result['order']['Currency'];
        $Amount = $result['order']['Amount'];
        $Code = $result['order']['Code'];
        $Status = $result['order']['Status'];
        $MD5info = $result['order']['MD5info'];

        $MD5src = trim($payConfig['app_key']) . trim($payConfig['tran_num']) . trim($OrderID) . trim($Currency) . trim($Amount) . trim($Code) . trim($Status);
        $MD5sign = strtoupper(md5($MD5src));
        if ($MD5sign == $MD5info) {
            //跳轉到支付成功頁面
            $url = SERVER_ROOT . 'success.php?order_sn=' . $result['order']['OrderID'];
            $ret = array("code" => 0, "url" => $url);

            updatePayInfo($result['order']['OrderID'], array("RetCode" => $result['order']['Code'], "RetMsg" => "支付成功", "RetStatus" => $result['order']['Status'], "modifytime" => time()));
            $mail_data = array("to_email" => (isset($data['DEmail']) ? $data['DEmail'] : $data['BEmail']), "order_sn" => $result['order']['OrderID'], "products_info" => $productsInfo, "createtime" => time());
            saveEmailData($mail_data);
        } else {
            //否則跳轉到失敗頁面，提示重新支付
            $msg = '返回值簽名解析錯誤';
            $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $result['order']['OrderID'];
            updatePayInfo($result['order']['OrderID'], array("RetCode" => $result['order']['Code'], "RetMsg" => $msg, "RetStatus" => $result['order']['Status'], "modifytime" => time()));

        }
    } elseif ($result['order']['Status'] == 4) {
        $msg = '正在處理中';
        $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $result['order']['OrderID'];
        $ret = array("code" => $result['order']['Code'], "url" => $url);
        updatePayInfo($result['order']['OrderID'], array("RetCode" => "", "RetMsg" => $msg, "RetStatus" => $result['order']['Status'], "modifytime" => time()));
    } else {//有錯誤
        $msg = '支付失敗';
        $url = SERVER_ROOT . 'failed.php?msg=' . $msg . '&order_sn=' . $result['order']['OrderID'];
        $ret = array("code" => $result['order']['Code'], "url" => $url);
        updatePayInfo($result['order']['OrderID'], array("RetCode" => "", "RetMsg" => $msg, "RetStatus" => $result['order']['Status'], "modifytime" => time()));
        //測試發郵件
//        $mail_data = array("to_email" => (isset($data['DEmail']) ? $data['DEmail'] : $data['BEmail']), "order_sn" => $result['order']['OrderID'], "products_info" => $productsInfo, "createtime" => time());
//        Utils::createLog(var_export($mail_data, true));
//        saveEmailData($mail_data);
    }
}

exit(json_encode($ret));